package com.fly.toolbox;

import com.fly.toolbox.bean.TaskInfo;
import com.fly.toolbox.component.GenerateVersionLogsComponent;
import com.fly.toolbox.constant.BankEnum;
import com.fly.toolbox.service.NoteFileService;
import com.fly.toolbox.service.impl.NoteFileServiceImpl;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Objects;

public class GenerateVersionLogsAction extends AnAction {

    private final NoteFileService noteFileService = new NoteFileServiceImpl();
    private GenerateVersionLogsComponent component;
    private TaskInfo taskInfo = null;
    private JBPopup popup;

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();
        VirtualFile[] virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY);
        Presentation presentation = e.getPresentation();
        ArrayList<VirtualFile> filePaths = new ArrayList<>();
        if (virtualFiles != null) {
            for (VirtualFile file : virtualFiles) {
                if (!new File(file.getPath()).isFile()) {
                    Messages.showErrorDialog("请选择文件！", "Error");
                    return;
                }
                filePaths.add(file);
            }
        }

        if (CollectionUtils.isEmpty(filePaths)) {
            return;
        }

        component = new GenerateVersionLogsComponent();
        component.setTextArea(noteFileService.generateSvnLog(taskInfo));
        setText(taskInfo);

        // 确认按钮点击事件
        component.getSubmitButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (taskInfo == null) {
                    taskInfo = new TaskInfo();
                }
                taskInfo.setOrderId(component.getRequirementNumberText());
                taskInfo.setBankName(component.getRequirementBankText());
                taskInfo.setBankAlias(BankEnum.parseBankAlias(taskInfo.getBankName()));
                taskInfo.setMessage(component.getRequirementDescriptionText());
                taskInfo.setTaskId(component.getChangeRequestNumberText());
                taskInfo.setVersion(component.getVersionComboBoxValue());
                if (StringUtils.isEmpty(taskInfo.getOrderId()) ||
                        StringUtils.isEmpty(taskInfo.getBankName()) ||
                        StringUtils.isEmpty(taskInfo.getMessage()) ||
                        StringUtils.isEmpty(taskInfo.getTaskId()) ||
                        StringUtils.isEmpty(taskInfo.getVersion())) {
                    Messages.showErrorDialog("任务信息不能为空！", "Error");
                    return;
                }
                for (VirtualFile file : filePaths) {
                    noteFileService.writeVersionLog(file, project, taskInfo);
                }

                // 关闭弹出式窗口
                popup.cancel();
            }
        });

        component.getDropdownButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                component.historyPopup(text -> {
                    component.setTextArea(text);
                    setText(noteFileService.parseTaskInfo(text, component.getVersionComboBoxValue()));
                });
            }
        });

        component.getParseButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setText(noteFileService.parseTaskInfo(component.getTextArea(), component.getVersionComboBoxValue()));
            }
        });

        if (popup != null && popup.isVisible()) {
            popup.cancel();
        }
        popup = JBPopupFactory.getInstance()
                .createComponentPopupBuilder(component.getPanel(), component.getPreferredFocusedComponent())
                .setTitle(presentation.getDescription())
                .setResizable(true)
                .setMovable(true)
                .setRequestFocus(true)
                .setCancelOnClickOutside(false)
                .setCancelOnWindowDeactivation(false) // 禁止切换窗口关闭
                .createPopup();
        popup.showCenteredInCurrentWindow(Objects.requireNonNull(project));

    }

    private void setText(TaskInfo taskInfo) {
        if (taskInfo == null) return;
        component.setRequirementNumberText(taskInfo.getOrderId());
        component.setRequirementBankText(taskInfo.getBankName());
        component.setRequirementDescriptionText(taskInfo.getMessage());
        component.setChangeRequestNumberText(taskInfo.getTaskId());
        component.setVersionComboBoxValue(taskInfo.getVersion());
    }

}
